package cn.edu.hit.registry.impl;

import cn.edu.hit.Constant;
import cn.edu.hit.registry.ServiceRegistry;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Zookeeper的服务注册实现
 * Created by 朱才海 on 2017/12/17.
 */
public class ZookeeperServiceRegistry implements ServiceRegistry{

    private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperServiceRegistry.class);

    //zookeeper客户端实例
    private final ZkClient zkClint;

    public ZookeeperServiceRegistry(String zkAddress){
        //初始化zookeeper实例
        zkClint = new ZkClient(zkAddress, Constant.ZK_SESSION_TIMEOUT, Constant.ZK_CONNECTION_TIMEOUT);
        LOGGER.debug("connect to zookeeperServer successfully");
    }

    public void register(String serviceName, String serviceAddress) {
        //创建registry持久节点
        String registryPath = Constant.ZK_REGISTRY_PATH;
        if(!zkClint.exists(registryPath)){
            zkClint.createPersistent(registryPath);
            LOGGER.debug("create registry node:" + registryPath);
        }

        //创建service持久节点
        String servicePath = registryPath + "/" + serviceName;
        if(!zkClint.exists(servicePath)){
            zkClint.createPersistent(servicePath);
            LOGGER.debug("create service node:" +  serviceAddress);
        }

        //创建address临时节点
        String addressPath  = servicePath + "/address-";
        String addressNode = zkClint.createEphemeralSequential(addressPath, serviceAddress);
        LOGGER.debug("create address node:" + addressNode);
    }
}
